﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

namespace NFLManager
{
    public class Utilities
    {

        protected Utilities(){}

        protected static Utilities _utilities = null;

        public static Utilities Istance
        {
            get { return _utilities ?? (_utilities = new Utilities()); }
        }

        public string CleanValue(string value)
        {
            string result = value.Replace(" ", "");
            result = Regex.Replace(result, @"\t|\n|\r|@", "");
            return result;
        }

        public object GetValue(string value)
        {
            float f = 0;
            int d = 0;

            //ho rimosso il tipo byte perchè dava problemi sulla creazione della LeadersDataTable.
            //Alcuni valori erano rilevati come byte, nella fase di tipizzazione dei campi della data table.
            //Tali valori erano troppo piccoli rispetto ai massimi che alcuni campi possono assumere.
            //es. receiving yards rilevato 15 -> byte  ma tale valore può assumere anche un numero maggiore di 250.
            //byte b = 0;
            //if (byte.TryParse(value, out b)) return b;

            if (Int32.TryParse(value, out d)) return d;
            if (Single.TryParse(value.Replace(".", ","), out f)) return f;

            return value;
        }

        public DataTable DataTableFromHtml(string dtTitle, HtmlNode nodes)
        {
            
            var thd1 = nodes.SelectNodes("//tr")
                .FirstOrDefault(d => d.Attributes.Contains("class") && d.Attributes["class"].Value == "thd1");

            var thd2 = nodes.SelectNodes("//tr")
                .FirstOrDefault(d => d.Attributes.Contains("class") && d.Attributes["class"].Value == "thd2");

            var th0s = nodes.SelectNodes("//th");

            var thds = thd1 != null ? thd1.SelectNodes("td") : (thd2 != null ? thd2.SelectNodes("td") : null);

            var ths = th0s ?? thds;

            var trs = nodes.SelectNodes("//tr");
            
            var result = new DataTable(dtTitle);

            var headers = ths.Select(th => th.InnerText.Trim());

            foreach (var header in headers)
            {
                result.Columns.Add(header);
            }

            var rows = trs.Skip(1).Select(tr => tr
                .Elements("td")
                .Select(td => td.InnerText.Trim())
                .ToArray());

            foreach (var row in rows)
            {
                result.Rows.Add(row);
            }

            //IEnumerable<HtmlNode> firstTitles = nodes.;
            //IEnumerable<HtmlNode> secondTitles = ;
            //IEnumerable<HtmlNode> values = ;
            //string colName = null;
            //Type colType;
            //int colSpan = 0;
            //int i = 0;
            

            //try
            //{
            //    switch (numberOfTitles)
            //    {
            //        case 1:

            //            firstTitles = table.Descendants("tr").ElementAt(0).Descendants("td");
            //            //todo
            //            //dovrei modificare la tabella players in maniera tale da non dover inserire la seguente riga di codice
            //            if (!firstTitles.Any()) firstTitles = table.Descendants("tr").ElementAt(0).Descendants("th");

            //            values = table.Descendants("tr").ElementAt(1).Descendants("td");

            //            i = 0;
            //            foreach (var col in firstTitles)
            //            {
            //                colName = Utilities.Istance.CleanValue(col.InnerText.ToUpper());
            //                if (result.Columns.Contains(colName)) colName = colName + i;
            //                colType = Utilities.Istance.GetValue(Utilities.Istance.CleanValue(values.ElementAt(i++).InnerText)).GetType();
            //                result.Columns.Add(colName, colType);
            //            }

            //            break;

            //        case 2:

            //            firstTitles = table.Descendants("tr").ElementAt(0).Descendants("td");
            //            secondTitles = table.Descendants("tr").ElementAt(1).Descendants("td");
            //            values = table.Descendants("tr").ElementAt(2).Descendants("td");

            //            i = 0;
            //            foreach (var col in firstTitles)
            //            {
            //                colSpan = colSpan + Int32.Parse(col.GetAttributeValue("colspan", ""));
            //                for (; i < colSpan; i++)
            //                {
            //                    colName = Utilities.Istance.CleanValue(col.InnerText).ToUpper() + "_" + Utilities.Istance.CleanValue(secondTitles.ElementAt(i).InnerText).ToUpper();
            //                    colType = Utilities.Istance.GetValue(Utilities.Istance.CleanValue(values.ElementAt(i).InnerText)).GetType();
            //                    if (result.Columns.Contains(colName)) colName = colName + i;
            //                    result.Columns.Add(colName, colType);
            //                }
            //            }

            //            break;
            //    }

            //    var rows = table.Descendants("tr").Skip(numberOfTitles);
            //    foreach (var row in rows)
            //    {
            //        var resultRow = result.NewRow();
            //        i = 0;
            //        foreach (var val in row.SelectNodes("td"))
            //        {
            //            resultRow[i++] = Utilities.Istance.GetValue(Utilities.Istance.CleanValue(val.InnerText));
            //        }
            //        result.Rows.Add(resultRow);
            //    }
            //    return result;
            //}
            //catch (Exception e)
            //{
            //    Logs.Istance.LogException("Fetch.GetDataTableFromHtmlTable", url, e, dtTitle, (result.Rows.Count + 1), i);
            //}
            return result;
        }
    }
}
